# myapp/consumers.py

import json
from channels.generic.websocket import AsyncWebsocketConsumer


class FileNotifyConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        print("🔗 连接成功")
        await self.channel_layer.group_add("file_watch_group", self.channel_name)
        await self.accept()

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard("file_watch_group", self.channel_name)

    async def receive(self, text_data):
        print(f"📩 接收到客户端消息: {text_data}")

    # 后端主动推送用这个函数
    async def send_new_file(self, event):
        print(f"📩 发送文件信息到客户端: {event['filename']}")
        await self.send(text_data=json.dumps({
            "filename": event["filename"],
        }))
